import SwiftUI
import PhotosUI
import CoreLocation
import Combine

// MARK: - 地点轴视图模型
@MainActor
class LocationAxisViewModel: ObservableObject {
    @Published var locationGroups: [LocationGroup] = []
    @Published var expandedGroups: Set<String> = []
    @Published var expandedSubGroups: Set<String> = []
    @Published var isLoading = false
    @Published var lastUpdateTime: Date = Date()
    
    private let locationGroupService = LocationGroupService()
    private var cancellables = Set<AnyCancellable>()
    
    init() {
        print("📍 [LocationAxisViewModel] 初始化地点轴视图模型")
        setupBindings()
    }
    
    // MARK: - 公共接口
    
    /// 更新照片数据并重新计算分组
    func updatePhotos(_ photos: [PhotoData]) {
        print("📍 [LocationAxisViewModel] 更新照片数据，数量: \(photos.count)")
        isLoading = true
        
        // 使用新的分组服务
        let groups = locationGroupService.getLocationGroups(from: photos)
        
        DispatchQueue.main.async {
            self.locationGroups = groups
            self.isLoading = false
            self.lastUpdateTime = Date()
            print("📍 [LocationAxisViewModel] 分组更新完成，数量: \(groups.count)")
        }
    }
    
    /// 强制刷新分组
    func forceRefresh() {
        print("🔄 [LocationAxisViewModel] 强制刷新分组")
        locationGroupService.forceRefresh()
        // 重新计算分组
        updatePhotos([]) // 这里需要传入当前照片数据
    }
    
    /// 清空所有分组
    func clearAllGroups() {
        print("🗑️ [LocationAxisViewModel] 清空所有分组")
        locationGroupService.clearAllGroups()
        locationGroups = []
        expandedGroups.removeAll()
        expandedSubGroups.removeAll()
    }
    
    /// 切换父节点展开状态
    func toggleParentGroup(_ groupId: String) {
        if expandedGroups.contains(groupId) {
            expandedGroups.remove(groupId)
        } else {
            expandedGroups.insert(groupId)
        }
        print("📍 [LocationAxisViewModel] 切换父节点: \(groupId), 展开状态: \(expandedGroups.contains(groupId))")
    }
    
    /// 切换子节点展开状态
    func toggleSubGroup(_ groupId: String) {
        if expandedSubGroups.contains(groupId) {
            expandedSubGroups.remove(groupId)
        } else {
            expandedSubGroups.insert(groupId)
        }
        print("📍 [LocationAxisViewModel] 切换子节点: \(groupId), 展开状态: \(expandedSubGroups.contains(groupId))")
    }
    
    // MARK: - 私有方法
    
    private func setupBindings() {
        // 监听分组服务的变化
        locationGroupService.$locationGroups
            .sink { [weak self] groups in
                self?.locationGroups = groups
            }
            .store(in: &cancellables)
        
        // 监听刷新通知
        NotificationCenter.default.publisher(for: NSNotification.Name("RefreshLocationAxis"))
            .sink { [weak self] _ in
                print("📍 [LocationAxisViewModel] 收到刷新通知")
                self?.handleRefresh()
            }
            .store(in: &cancellables)
    }
    
    private func handleRefresh() {
        // 这里可以添加刷新逻辑
        print("📍 [LocationAxisViewModel] 处理刷新事件")
    }
}

// MARK: - 新的地点轴主视图
struct LocationAxisNewView: View {
    @StateObject private var viewModel = LocationAxisViewModel()
    @EnvironmentObject var photoService: PhotoService
    
    var body: some View {
        NavigationView {
            VStack(spacing: 0) {
                // 顶部统计信息
                if !photoService.photos.isEmpty {
                    StatisticsHeaderViewNew(photoService: photoService, locationGroups: viewModel.locationGroups)
                        .padding(.horizontal, 16)
                        .padding(.top, 20)
                }
                
                // 加载状态
                if viewModel.isLoading {
                    LoadingView()
                        .frame(maxWidth: .infinity, maxHeight: .infinity)
                } else {
                    // 地点组列表
                    ScrollView {
                        LazyVStack(spacing: 20) {
                            ForEach(viewModel.locationGroups.filter { $0.isParentNode }) { parentGroup in
                                LocationGroupNewCard(
                                    group: parentGroup,
                                    isExpanded: viewModel.expandedGroups.contains(parentGroup.id),
                                    onToggle: {
                                        viewModel.toggleParentGroup(parentGroup.id)
                                    }
                                )
                                .environmentObject(photoService)
                                
                                // 子节点列表
                                if viewModel.expandedGroups.contains(parentGroup.id) {
                                    childGroupsView(for: parentGroup)
                                }
                            }
                        }
                        .padding(.horizontal, 16)
                        .padding(.top, 20)
                    }
                }
            }
            .navigationTitle("地点回忆 (新)")
            .navigationBarTitleDisplayMode(.large)
            .toolbar {
                toolbarContent
            }
        }
        .onReceive(NotificationCenter.default.publisher(for: NSNotification.Name("RefreshLocationAxis"))) { _ in
            print("📍 [LocationAxisNewView] 收到刷新通知")
            viewModel.forceRefresh()
        }
        .onAppear {
            // 初始化时更新照片数据
            viewModel.updatePhotos(photoService.photos)
        }
        .onChange(of: photoService.photos) { _, newPhotos in
            // 照片数据变化时更新分组
            viewModel.updatePhotos(newPhotos)
        }
    }
    
    @ViewBuilder
    private func childGroupsView(for parentGroup: LocationGroup) -> some View {
        let childGroups = viewModel.locationGroups.filter { 
            !$0.isParentNode && $0.parentCity == parentGroup.city 
        }
        
        VStack(spacing: 8) {
            ForEach(childGroups) { childGroup in
                LocationSubGroupNewCard(
                    group: childGroup,
                    isExpanded: viewModel.expandedSubGroups.contains(childGroup.id),
                    onToggle: {
                        viewModel.toggleSubGroup(childGroup.id)
                    }
                )
                .environmentObject(photoService)
            }
        }
        .padding(.leading, 20)
        .transition(.opacity.combined(with: .scale(scale: 0.95)))
    }
    
    private var toolbarContent: some ToolbarContent {
        Group {
            ToolbarItem(placement: .navigationBarLeading) {
                Button("返回旧视图") {
                    NotificationCenter.default.post(name: NSNotification.Name("ShowOldLocationAxis"), object: nil)
                }
                .foregroundColor(.blue)
            }
            
            ToolbarItem(placement: .navigationBarTrailing) {
                HStack(spacing: 16) {
                    // 刷新按钮
                    Button(action: {
                        viewModel.forceRefresh()
                    }) {
                        Image(systemName: "arrow.clockwise")
                            .font(.title2)
                            .foregroundColor(.blue)
                    }
                
                // 清空按钮
                Button(action: {
                    viewModel.clearAllGroups()
                }) {
                    Image(systemName: "trash")
                        .font(.title2)
                        .foregroundColor(.red)
                }
            }
        }
        }
    }
}

// MARK: - 新的父节点卡片
struct LocationGroupNewCard: View {
    let group: LocationGroup
    let isExpanded: Bool
    let onToggle: () -> Void
    @EnvironmentObject var photoService: PhotoService
    
    var body: some View {
        VStack(spacing: 0) {
            Button(action: onToggle) {
                HStack {
                    // 国旗和地点信息
                    HStack(spacing: 12) {
                        Text(getCountryFlag(for: group.country))
                            .font(.title2)
                        
                        VStack(alignment: .leading, spacing: 4) {
                            Text(group.displayName)
                                .font(.headline)
                                .foregroundColor(.primary)
                            
                            Text(getDateRangeText(for: group.photos))
                                .font(.caption)
                                .foregroundColor(.secondary)
                        }
                    }
                    
                    Spacer()
                    
                    // 照片数量
                    Text("\(group.totalPhotos)张")
                        .font(.caption)
                        .foregroundColor(.blue)
                        .padding(.horizontal, 8)
                        .padding(.vertical, 4)
                        .background(Color.blue.opacity(0.1))
                        .cornerRadius(6)
                    
                    // 展开/收缩图标
                    Image(systemName: isExpanded ? "chevron.up" : "chevron.down")
                        .font(.caption)
                        .foregroundColor(.secondary)
                        .rotationEffect(.degrees(isExpanded ? 0 : 0))
                        .animation(.easeInOut(duration: 0.3), value: isExpanded)
                }
                .padding()
                .background(
                    RoundedRectangle(cornerRadius: 12)
                        .fill(Color(.systemBackground))
                        .shadow(color: .black.opacity(0.1), radius: 2, x: 0, y: 1)
                )
            }
            .buttonStyle(PlainButtonStyle())
            .scaleEffect(isExpanded ? 1.02 : 1.0)
            .animation(.easeInOut(duration: 0.2), value: isExpanded)
        }
        .onAppear {
            print("📍 [LocationGroupNewCard] 渲染父节点: \(group.city) [\(group.totalPhotos)张]")
        }
    }
    
    private func getCountryFlag(for country: String) -> String {
        let flagMap: [String: String] = [
            "中国": "🇨🇳",
            "日本": "🇯🇵",
            "韩国": "🇰🇷",
            "美国": "🇺🇸",
            "英国": "🇬🇧",
            "法国": "🇫🇷",
            "德国": "🇩🇪",
            "意大利": "🇮🇹",
            "西班牙": "🇪🇸",
            "加拿大": "🇨🇦",
            "澳大利亚": "🇦🇺"
        ]
        return flagMap[country] ?? "🏳️"
    }
    
    private func getDateRangeText(for photos: [PhotoData]) -> String {
        guard !photos.isEmpty else { return "无日期信息" }
        
        let dates = photos.map { $0.creationDate }
        guard let minDate = dates.min(),
              let maxDate = dates.max() else {
            return "无日期信息"
        }
        
        let formatter = DateFormatter()
        formatter.dateFormat = "yyyy-MM"
        
        let startDate = formatter.string(from: minDate)
        let endDate = formatter.string(from: maxDate)
        
        if startDate == endDate {
            return startDate
        } else {
            return "\(startDate) - \(endDate)"
        }
    }
}

// MARK: - 新的子节点卡片
struct LocationSubGroupNewCard: View {
    let group: LocationGroup
    let isExpanded: Bool
    let onToggle: () -> Void
    @EnvironmentObject var photoService: PhotoService
    
    var body: some View {
        VStack(spacing: 0) {
            Button(action: onToggle) {
                HStack {
                    // 缩进指示
                    Rectangle()
                        .fill(Color.gray.opacity(0.3))
                        .frame(width: 4, height: 40)
                        .cornerRadius(2)
                    
                    // 地点信息
                    VStack(alignment: .leading, spacing: 2) {
                        Text(group.detailedLocation ?? group.city)
                            .font(.subheadline)
                            .foregroundColor(.primary)
                        
                        Text(getDateRangeText(for: group.photos))
                            .font(.caption)
                            .foregroundColor(.secondary)
                    }
                    
                    Spacer()
                    
                    // 照片数量
                    Text("\(group.totalPhotos)张")
                        .font(.caption)
                        .foregroundColor(.blue)
                        .padding(.horizontal, 8)
                        .padding(.vertical, 4)
                        .background(Color.blue.opacity(0.1))
                        .cornerRadius(6)
                    
                    // 展开/收缩图标
                    Image(systemName: isExpanded ? "chevron.up" : "chevron.down")
                        .font(.caption)
                        .foregroundColor(.secondary)
                        .rotationEffect(.degrees(isExpanded ? 0 : 0))
                        .animation(.easeInOut(duration: 0.3), value: isExpanded)
                }
                .padding(.horizontal, 16)
                .padding(.vertical, 8)
                .background(
                    RoundedRectangle(cornerRadius: 8)
                        .fill(Color(.systemGray6))
                        .overlay(
                            RoundedRectangle(cornerRadius: 8)
                                .stroke(Color.blue.opacity(0.3), lineWidth: 1)
                        )
                )
            }
            .buttonStyle(PlainButtonStyle())
            .scaleEffect(isExpanded ? 1.02 : 1.0)
            .animation(.easeInOut(duration: 0.2), value: isExpanded)
            
            // 照片网格（仅在展开时显示）
            if isExpanded {
                LazyVGrid(columns: Array(repeating: GridItem(.flexible(), spacing: 4), count: 4), spacing: 4) {
                    ForEach(group.photos.prefix(12)) { photo in
                        OptimizedPhotoThumbnail(
                            photo: photo,
                            size: CGSize(width: 60, height: 60),
                            cornerRadius: 6
                        ) {
                            // 点击照片的处理
                        }
                    }
                }
                .padding(.top, 8)
                .transition(.opacity.combined(with: .scale(scale: 0.95)))
            }
        }
        .padding(.leading, 20)
        .animation(.easeInOut(duration: 0.3), value: isExpanded)
        .onAppear {
            print("📍 [LocationSubGroupNewCard] 渲染子节点: \(group.detailedLocation ?? "nil") [\(group.totalPhotos)张]")
        }
    }
    
    private func getDateRangeText(for photos: [PhotoData]) -> String {
        guard !photos.isEmpty else { return "未知日期" }
        
        let sortedPhotos = photos.sorted { $0.creationDate < $1.creationDate }
        let firstDate = sortedPhotos.first!.creationDate
        let lastDate = sortedPhotos.last!.creationDate
        
        let formatter = DateFormatter()
        formatter.dateFormat = "MM月dd日"
        
        let startDate = formatter.string(from: firstDate)
        let endDate = formatter.string(from: lastDate)
        
        if Calendar.current.isDate(firstDate, inSameDayAs: lastDate) {
            return startDate
        } else {
            return "\(startDate) - \(endDate)"
        }
    }
}

// MARK: - 统计头部视图（新版本）
struct StatisticsHeaderViewNew: View {
    @ObservedObject var photoService: PhotoService
    let locationGroups: [LocationGroup]
    
    private var dateRangeText: String? {
        let statistics = PhotoStatistics(photos: photoService.photos)
        guard let dateRange = statistics.dateRange else { return nil }
        
        let formatter = DateFormatter()
        formatter.dateFormat = "yyyy年MM月"
        let startDate = formatter.string(from: dateRange.lowerBound)
        let endDate = formatter.string(from: dateRange.upperBound)
        
        return startDate == endDate ? startDate : "\(startDate) - \(endDate)"
    }
    
    var body: some View {
        VStack(spacing: 12) {
            HStack {
                VStack(alignment: .leading, spacing: 4) {
                    Text("\(photoService.photos.filter { $0.location != nil }.count)")
                        .font(.title2)
                        .fontWeight(.bold)
                        .foregroundColor(.orange)
                    
                    Text("有地理信息照片")
                        .font(.caption)
                        .foregroundColor(.secondary)
                }
                
                Spacer()
                
                VStack(alignment: .center, spacing: 4) {
                    Text("\(photoService.photos.filter { $0.location != nil }.count)")
                        .font(.title2)
                        .fontWeight(.bold)
                        .foregroundColor(.blue)
                    
                    Text("有地理信息照片")
                        .font(.caption)
                        .foregroundColor(.secondary)
                }
                
                Spacer()
                
                VStack(alignment: .trailing, spacing: 4) {
                    Text("\(locationGroups.filter { $0.isParentNode }.count)")
                        .font(.title2)
                        .fontWeight(.bold)
                        .foregroundColor(.green)
                    
                    Text("个地点")
                        .font(.caption)
                        .foregroundColor(.secondary)
                }
            }
            
            if let dateRangeText = dateRangeText {
                Text("时间跨度: \(dateRangeText)")
                    .font(.caption)
                    .foregroundColor(.secondary)
            }
        }
        .padding()
        .background(Color(.systemGray6))
        .cornerRadius(12)
    }
} 